package cn.edu.hqu.javaee.springboot_sql.controller;

import cn.edu.hqu.javaee.springboot_sql.entity.User;
import cn.edu.hqu.javaee.springboot_sql.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Optional;

@Controller
@RequestMapping("/user")
public class userController {
    @Autowired
    // This means to get the bean called userRepository
    // Which is auto-generated by Spring, we will use it to handle the data
    private UserRepository userRepository;


//    @PostMapping("/add") //暂时用地址拼接的方式传过去是get方法，用post的话暂时不会
    @RequestMapping("/add")
    public @ResponseBody String addNewUser(@RequestParam String username, @RequestParam String name,
                                           @RequestParam Short age,@RequestParam BigDecimal balance){
    // @ResponseBody means the returned String is the response, not a view name
    // @RequestParam means it is a parameter from the GET or POST request
        User n = new User();
        n.setUsername(username);
        n.setName(name);
        n.setAge(age);
        n.setBalance(balance);
        userRepository.save(n);
        return "Saved";
    }

    @GetMapping("/all")
    public  @ResponseBody Iterable<User> getAllUsers(){
        // This returns a JSON or XML with the users
        return userRepository.findAll();
    }

    @GetMapping("/{id}")
    public Optional<User> findById(@PathVariable Long id){
        return this.userRepository.findById(id);
    }

}
